package com.lzc.camera.service;


import com.lzc.camera.entity.Config;
import com.lzc.camera.entity.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

@Component
@Async
@Slf4j
public class AsynsJob {

    @Value("${image.dvrPicSavePath}")
    private String savePath;

    @Autowired
    private LogService logService;

    public void synMethod() {
        try {
            //模拟业务处理
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我是异步方法");
    }

    /**
     * 下载图片步骤（异步处理）
     *
     * @param ipAddress
     * @param fileName
     * @param config
     */
    public void getImage(String ipAddress, String fileName, Config config) {
        try {
            // 构造URL
            //http://192.168.188.10/snapshot.cgi/stream=1
            String url = "https://" + ipAddress + "/snapshot.cgi/stream=1";
            //测试使用地址
//            String url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202101%2F21%2F20210121214250_7c989.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1671607289&t=f9f9d2c44c2ad415a50f7248214f4912";
            // 打开连接
            URLConnection con = new URL(url).openConnection();
            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
//        String filename = "D:\\image/" + fileName + ".jpg";  //下载路径及下载图片名称
            String filename = savePath + fileName + ".jpg";  //下载路径及下载图片名称
            File file = new File(filename);
            FileOutputStream os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Log logmsg = new Log();
        logmsg.setCreationTime(LocalDateTime.now());
        logmsg.setFileName(fileName);
        logmsg.setIpAddress(ipAddress);
        logmsg.setPointKey(config.getPointKey());
        logmsg.setPointName(config.getPointName());
        boolean save = logService.save(logmsg);
        if (!save) {
            log.error("保存失败" + logmsg.toString());
        }
        log.info("保存成功" + logmsg.toString());
    }

    public void deleteFile() {
        File file = new File(savePath);
        //文件或文件夹是否存在
        if (file.exists()) {
            //判断是不是目录
            if (file.isDirectory()) {
                info(file);
            }
        }
    }

    public static void info(File file) {
        //得到文件里面全部的文件及文件夹
        File[] files = file.listFiles();

        //遍历files里面的全部文件及文件夹
        for (File f : files) {
            //得到绝对路径下的文件及文件夹
            File absFile = f.getAbsoluteFile();
            //当前时间
            long currTime = System.currentTimeMillis();
            //文件被最后一次修改的时间
            long lastTime = absFile.lastModified();
            //时间差
            long diffen = currTime - lastTime;
            if (diffen > 1000 * 60 * 60 * 24 * 180) {
                absFile.delete();
                if (absFile.isDirectory()) {
                    info(absFile);
                    absFile.delete();
                }
            }
        }
    }
}


